
package biblio.service.category;


import biblio.bean.CategoryBean;
import biblio.dao.CategoryDAO;
import biblio.domain.Category;
import biblio.exception.NoSuchEntityException;
import biblio.util.SourceName;
import biblio.util.interfaces.RequestOperationHelper;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;


/**
 * Services for operation on entity Category.
 * 
 * @author mephisto
 */
@ManagedBean(name="catService")
@ApplicationScoped
public class CategoryServiceImpl implements CategoryService
{
    public String create()
    {
        RequestOperationHelper rOH = (RequestOperationHelper)appContext.getBean("rOH");
        categoryBean = (CategoryBean) rOH.getBean("catBean");
        CategoryDAO categoryDAO = (CategoryDAO)appContext.getBean("catDAO");
        Category cat = new Category();
        cat.setName(categoryBean.getName());
        Category masterCategory = null;
        try 
        {
           masterCategory = categoryDAO.find(categoryBean.getMasterName());
           log.debug("Id of master category: " + masterCategory.getId());
           cat.setMasterId(masterCategory.getId());
        }
        catch (NoSuchEntityException e)
        {
           log.warn("No such master category! It should not happen");
           return "";
        }
        categoryDAO.create(cat);
        categoryBean.clear();
        return "";
    }

    public void update(Category category)
    {
        log.debug("Category to update: " + category.getId() + ", " + category.getName());

        CategoryDAO categoryDAO = (CategoryDAO)appContext.getBean("catDAO");
        try
        {
            categoryDAO.update(category);
        }
        catch (NoSuchEntityException ex)
        {
            log.error("Entity with id: " + category.getId() + "does not exist in the database");
            log.error(ex.getMessage());
        }
    }

    public void delete(Category category)
    {
        CategoryDAO categoryDAO = (CategoryDAO)appContext.getBean("catDAO");
        try
        {
            categoryDAO.delete(category);
        }
        catch(DataAccessException e)
        {
            log.error("Entity with id: " + category.getId() + "does not exist in the database");
            log.error(e);
        }
    }

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.AUX_APPLICATION_CONTEXT,
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(CategoryServiceImpl.class);
    private CategoryBean categoryBean;
}
